package struct.string;

import java.util.Arrays;

/**
 * @author: kanggw
 * @date: 2022/4/27
 * @DESCRIPTION: 给定两个字符串 s 和 t ，编写一个函数来判断 t 是否是 s 的字母异位词。
 * <p>
 * 注意：若 s 和 t 中每个字符出现的次数都相同，则称 s 和 t 互为字母异位词。
 * <p>
 * 输入: s = "anagram", t = "nagaram"
 * 输出: true
 */
public class Anagram {

    public boolean isAnagramOne(String s1, String s2) {

        char[] chars1 = s1.toCharArray();
        char[] chars2 = s2.toCharArray();
        Arrays.sort(chars1);
        Arrays.sort(chars2);

        return Arrays.equals(chars1, chars2);
    }

    public boolean isAnagramTwo(String s1, String s2) {

        int[] table = new int[26];

        for (int i = 0; i < s1.length(); i++) {
            table[s1.charAt(i) - 'a']++;
        }

        for (int i = 0; i < s2.length(); i++) {
            if (--table[s2.charAt(i) - 'a']  < 0) {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
        Anagram anagram = new Anagram();

        String s = "anagram", t = "nagaram";
        String  s1 = "rat", t1 = "car";

        final boolean anagramOne = anagram.isAnagramOne(s1, t1);
        final boolean isAnagramTwo = anagram.isAnagramTwo(s1, t1);

        System.out.println("out:" + anagramOne);
        System.out.println("out:" + isAnagramTwo);
    }
}
